package com.ruoyi.business.controller;

import com.ruoyi.business.mapper.WsdRechargeRefundMapper;
import com.ruoyi.business.service.IWsdPaymentRecordsService;
import com.ruoyi.business.service.IWsdRechargeRefundService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WsdPaymentRecords;
import com.ruoyi.common.core.domain.entity.WsdRechargeRefund;
import com.ruoyi.common.core.domain.table.WsdPaymentRecordsTable;
import com.ruoyi.common.core.domain.vo.RechargeRefundVO;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.date.DateTimeUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 学期充值退款配置Controller
 *
 * @author ruoyi
 * @date 2024-05-21
 */
@RestController
@RequestMapping("wsd_refund")
public class WsdRechargeRefundController extends BaseController {

    @Autowired
    private IWsdRechargeRefundService wsdRechargeRefundService;
    @Autowired
    private WsdRechargeRefundMapper wsdRechargeRefundMapper;
    @Autowired
    private IWsdPaymentRecordsService wsdPaymentRecordsService;
    /**
     * 查询充值退款配置列表
     */
    @PreAuthorize("@ss.hasPermi('business:refund:list')")
    @GetMapping("/list")
    public TableDataInfo list(WsdRechargeRefund wsdRechargeRefund) {
        startPage(); SysUser user = getLoginUser().getUser();
        Long schoolId = user.getSchoolId();
        wsdRechargeRefund.setSchoolId(schoolId);
        List<WsdRechargeRefund> list = wsdRechargeRefundService.selectWsdRechargeRefundList(wsdRechargeRefund);
        return getDataTable(list);
    }

    /**
     * 导出充值退款配置列表
     */
    @PreAuthorize("@ss.hasPermi('business:refund:export')")
    @Log(title = "充值退款配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WsdRechargeRefund wsdRechargeRefund) {
        List<WsdRechargeRefund> list = wsdRechargeRefundService.selectWsdRechargeRefundList(wsdRechargeRefund);
        ExcelUtil<WsdRechargeRefund> util = new ExcelUtil<WsdRechargeRefund>(WsdRechargeRefund.class);
        util.exportExcel(response, list, "充值退款配置数据");
    }

    /**
     * 获取充值退款配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:refund:query')")
    @GetMapping(value = "/{configId}")
    public AjaxResult getInfo(@PathVariable("configId") Long configId) {
        return success(wsdRechargeRefundService.selectWsdRechargeRefundByConfigId(configId));
    }

    /**
     * 新增充值退款配置
     */
    @PreAuthorize("@ss.hasPermi('business:refund:add')")
    @Log(title = "充值退款配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WsdRechargeRefund wsdRechargeRefund) {
        SysUser user = getLoginUser().getUser();
        Long schoolId = user.getSchoolId();
        wsdRechargeRefund.setSchoolId(schoolId);
        wsdRechargeRefund.setCreatedAt(new Date());
        wsdRechargeRefund.setCreatedBy(user.getUserId().toString());
        // 获取当前日期
        LocalDate endDate = wsdRechargeRefund.getEndDate();
        LocalDate startDate = wsdRechargeRefund.getStartDate();
        // 将当前日期格式化为字符串
        String end = LocalDate.parse(endDate.toString()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String start = LocalDate.parse(startDate.toString()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //查询当前时间有没有配置
        RechargeRefundVO rechargeRefundVO  = wsdRechargeRefundService.existsActive(schoolId,end,start);
        if (rechargeRefundVO != null){
            return AjaxResult.warn("当前时间段已经配置过，请先删除再进行配置");
        }
        return toAjax(wsdRechargeRefundService.insertWsdRechargeRefund(wsdRechargeRefund));
    }

    /**
     * 修改充值退款配置
     */
    @PreAuthorize("@ss.hasPermi('business:refund:edit')")
    @Log(title = "充值退款配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WsdRechargeRefund wsdRechargeRefund) {
        //充值退款配置
        return toAjax(wsdRechargeRefundService.updateWsdRechargeRefund(wsdRechargeRefund));
    }

    /**
     * 修改充值退款配置状态
     */
    @PreAuthorize("@ss.hasPermi('business:refund:edit')")
    @Log(title = "充值退款配置状态", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody WsdRechargeRefund wsdRechargeRefund)
    {
        SysUser user = getLoginUser().getUser();
        if("1".equals( wsdRechargeRefund.getIsActive() )) {
            String currentDateString = DateTimeUtil.getCurrentDateString();
            RechargeRefundVO rechargeRefundVO = wsdRechargeRefundService.existsActiveSemester(user.getSchoolId(),currentDateString);
            if (rechargeRefundVO != null){
                return AjaxResult.warn("当前时间段已经有配置正在进行中，请先停用再进行配置");
            }
            wsdRechargeRefund.setIsActive( 1 );
        }
        wsdRechargeRefund.setUpdateBy(user.getUserName());
        return toAjax(wsdRechargeRefundService.updateWsdRechargeRefund(wsdRechargeRefund));
    }

    /**
     * 删除充值退款配置
     */
    @PreAuthorize("@ss.hasPermi('business:refund:remove')")
    @Log(title = "充值退款配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{configIds}")
    public AjaxResult remove(@PathVariable Long[] configIds) {
        return toAjax(wsdRechargeRefundService.deleteWsdRechargeRefundByConfigIds(configIds));
    }

    /**
     * 获取充值金额/是否缴费
     */
    @Anonymous
    @GetMapping(value = "/getRecharge/{studentId}")
    public AjaxResult getRecharge(@PathVariable("studentId") Long studentId) {
        WsdPaymentRecordsTable wsdPaymentRecordsTable = new WsdPaymentRecordsTable();
        Long schoolId = getLoginUser().getUser().getSchoolId();
        String currentDateString = DateTimeUtil.getCurrentDateString();
        RechargeRefundVO rechargeRefundVO = wsdRechargeRefundMapper.existsActiveSemester(currentDateString,schoolId);
        if (rechargeRefundVO != null){
            //本学期有配置收费项目
            WsdPaymentRecords wsdPaymentRecords = new WsdPaymentRecords();
            wsdPaymentRecords.setStudentId(studentId);
            wsdPaymentRecords.setConfigId( rechargeRefundVO.getConfigId() );
            wsdPaymentRecords.setSchoolsId( schoolId );
            List<WsdPaymentRecords> wsdPaymentRecords1 = wsdPaymentRecordsService.wsdPaymentRecords(wsdPaymentRecords);
            if (wsdPaymentRecords1.size()!=0){
                //已缴费
                wsdPaymentRecordsTable.setPaymentStatus( 1 );
            }else {
                BeanUtils.copyProperties(rechargeRefundVO, wsdPaymentRecordsTable);
                //未缴费（计算缴费金额）
                wsdPaymentRecordsTable.setPaymentStatus( 0 );
                wsdPaymentRecordsTable.setAllFee( wsdPaymentRecordsTable.getTotalBreakfastFee()
                        .add( wsdPaymentRecordsTable.getTotalLunchFee() )
                        .add( wsdPaymentRecordsTable.getTotalDinnerFee() ) );
            }
        }else {
            //没有配置
            wsdPaymentRecordsTable.setPaymentStatus( 0 );
        }
        return success(wsdPaymentRecordsTable);
    }
}
